/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var reverseKGroup1 = function (head, k) {
    if(head.next === null) return head
    let arr = []
    let p = head
    while(p) {
        arr.push(p)
        p = p.next
    }
    let n = Math.floor(arr.length / k)
    let middle = Math.floor(k / 2)
    for(let i = 0; i < n; i++) {
        for(let j = 0; j < middle; j++) {
            let temp = arr[j + i * k]
            arr[j + i * k] = arr[(i + 1) * k - j - 1]
            arr[(i + 1) * k - j - 1] = temp
        }
        // break
    }
    for(let i = 0; i < arr.length - 1; i++) {
        arr[i].next = arr[i + 1]
    }
    arr[arr.length - 1].next = null
    return arr[0]
};
// 空间O(1)
var reverseKGroup2 = function (head, k) {
    if (head.next === null || k == 1) return head
    let p = head, q = head.next, r = q
    let count = 2
    const iter = (p, q, r) => {
        if (p == r) {
            return
        }
        let temp = r.next
        r.next = p
        p.next = temp
        p = q
        q = p.next
        iter(p, q)
    }
    while (r.next) {
        while (count < k && r.next) {
            r = r.next
            count++
        }
        let nextP = r.next
        if (r) {
            iter(p, q, r)
            count = 1
            if(nextP && nextP.next) {
                p = nextP
                q = p.next
                r = q
            }
        }
    }
    return r
};